package com.ay.weixin.fdc.boss.project.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.json.JList;
import org.lizar.util.StringHelper;
import org.lizar.util.http.Http;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.FDCProjectFit;
import com.ay.weixin.config.types.FDCProjectStatus;
import com.ay.weixin.config.types.FDCProjectType;
import com.ay.weixin.fdc.admin.category.domain.Category;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectGrahDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;

public class ProjectMC extends Event {

	private IbatisProjectDao project_dao;
	private CategoryLoader cl;
	private IbatisProjectGrahDao grah_dao;
	
	private ProjectGrahMC grah_mc;
	
	
	
	@Override
	public void init_property() throws Exception {
		project_dao=Container.get(IbatisProjectDao.class);
		cl=Container.get(CategoryLoader.class);
		grah_dao=Container.get(IbatisProjectGrahDao.class);
		grah_mc=Container.get(ProjectGrahMC.class);
		
		
		
		
	}

	@Override
	public String default_handling_path() {
		return "/mc/fdc/project/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer adm=(Customer)el.getSessionAttr("customer");
		if(adm==null){
			el.response_to_root(CustomerLogin.login_path());
		}else{
			try{	
				if(el.queryPathCheck(3, "")){
					index(el,adm.getWxprojectID());
				}else if(el.queryPathCheck(3, "add_prepare")){
					add_prepare(el);
				}else if(el.queryPathCheck(3, "detail")){
					detail(el,adm.getWxprojectID());
				}else if(el.queryPathCheck(3, "add")){
					add(el,adm.getWxprojectID());
				}else if(el.queryPathCheck(3, "delete")){
					delete(el,adm.getWxprojectID());
				}else if(el.queryPathCheck(3, "update")){
					update(el,adm.getWxprojectID());
				}else if(el.queryPathCheck(3, "update_status")){
					update_status(el,adm.getWxprojectID());
				
				}
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("fdc.project.db.failure"));
				index(el,adm.getWxprojectID());
			}
			
		}
	}
	
	private void detail(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long id=el.getLong("id",-1);
		if(id==-1){
			id=el.getAttr("id",-1l);
		}
		if(id==-1){
			index(el,wxproject_id);
			return;
		}
		
		FDCProject project=project_dao.get(id);
		
		el.setAttr("project",project);
		
		el.setAttr("status_list", FDCProjectStatus.values());
		el.setAttr("property_type_list", FDCProjectType.values());
		el.setAttr("fit_list", FDCProjectFit.values());
		el.setAttr("property_list", cl.get("property").values());
		el.setAttr("location_category_list", cl.get("location").values());
		el.setAttr("location_json", toJson(cl.get("location").values()));
		
		el.template("/WEB-INF/template/boss/fdc/project/detail.vm");
	}
	
	private void add_prepare(EventLoader el) throws IOException, ServletException{
		
		el.setAttr("status_list", FDCProjectStatus.values());
		el.setAttr("property_type_list", FDCProjectType.values());
		el.setAttr("fit_list", FDCProjectFit.values());
		el.setAttr("property_list", cl.get("property").values());
		el.setAttr("location_category_list", cl.get("location").values());
		el.setAttr("location_json", toJson(cl.get("location").values()));
		el.template("/WEB-INF/template/boss/fdc/project/add.vm");
	}
	
	public String toJson(Collection<Category> clist){
		Iterator<Category> itr=clist.iterator();
		JList list=new JList();
		Category c=null;
		for(;itr.hasNext();){
			c=itr.next();
			list.add(c.toJSon());
		}
		return list.toString();
	}
	
	private void index(EventLoader el,long wxproject_id) throws IOException, ServletException{
		int category_id=el.getInt("category");
		List<FDCProject> list=null;
		if(cl.get(category_id)==null){
			try {
				list=project_dao.getAllByWxprojectId(wxproject_id);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("fdc.project.db.failure"));
			}
		}else{
			try {
				list=project_dao.getByCategory(wxproject_id,category_id);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("fdc.project.db.failure"));
			}
			el.setAttr("category_id", category_id);
		}
		
		
		el.setAttr("list", list);
		el.setAttr("property_list", cl.get("property").values());
		el.setAttr("status_list", FDCProjectStatus.values());
		el.template("/WEB-INF/template/boss/fdc/project/index.vm");
	}
	
	private void add(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		boolean isMultipart = ServletFileUpload.isMultipartContent(el.request());
        if(!isMultipart){
        	index(el,wxproject_id);
        	return;
        }
        String msg=null;
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        FilePostForm post_form=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
        post_form.setAllParamToAttr(el);
        if(post_form.getErrorMsg()!=null){
        	 msg=el.i18("fdc.project.image.upload.failed")+","+post_form.getErrorMsg();
        	 el.setAttr("msg",msg);
             add_prepare(el);
             return;
        }
        FileItem pic=post_form.getFileItem(0);
        if(pic==null){
        	 msg=el.i18("fdc.project.image.upload.nofile.found");
        	 el.setAttr("msg",msg);
       	  	 add_prepare(el);
             return;
        }
        if(!pic.getName().toLowerCase().endsWith(".jpg")){
        	 msg=el.i18("fdc.project.image.postfix.notsupport");
        	 el.setAttr("msg",msg);
       	  	 add_prepare(el);
             return;
        }
        File savedFile=new File(file_path);
        if(!savedFile.getParentFile().exists()){
          	 savedFile.getParentFile().mkdirs();
        }
        
        String title=post_form.getStr("title");
        String introduction=post_form.getStr("introduction");
        String traffic=post_form.getStr("traffic");
        String project_detail=post_form.getStr("project_detail");
        String location=post_form.getStr("location");
        String location_pic=post_form.getStr("location_pic");
        float manager_on_visit_bonus=post_form.getFloat("manager_on_visit_bonus",0);
        float old_cus_on_visit_bonus=post_form.getFloat("old_cus_on_visit_bonus",0);
        float manager_sales_rate=post_form.getFloat("manager_sales_rate",0);
        float old_cus_sales_rate=post_form.getFloat("old_cus_sales_rate",0);
        String manager_sales_return_desc=post_form.getStr("manager_sales_return_desc");
        String old_cus_sales_return_desc=post_form.getStr("old_cus_sales_return_desc");
        String property_type_desc=post_form.getStr("property_type_desc");
        int category=post_form.getInt("category",0);
        int status=post_form.getInt("status",FDCProjectStatus.readytosale.getCode());
        String contact=post_form.getStr("contact");
        String price=post_form.getStr("price");
        String developer=post_form.getStr("developer");
        String property_company=post_form.getStr("property_company");
        int property_type=post_form.getInt("property_type");
        int fit=post_form.getInt("fit");
        int year_limit=post_form.getInt("year_limit");
        int locate1=post_form.getInt("locate1");
        int locate2=post_form.getInt("locate2");
        int locate3=post_form.getInt("locate3");
        
        if(StringHelper.isNull(title)){
			msg=el.i18("fdc.project.title.cannot.be.empty");
			el.setAttr("msg",msg);
			add_prepare(el);
			return;
		}
        
        if(StringHelper.isNull(location)){
			msg=el.i18("fdc.project.location.cannot.be.empty");
			el.setAttr("msg",msg);
			add_prepare(el);
			return;
		}
        
		if(title.length()>Keys.getInt("fdc_project_validation.title_max_length")){
			msg=String.format(el.i18("fdc.project.title.max.length.exceed"),Keys.getInt("fdc_project_validation.title_max_length"));
			el.setAttr("msg",msg);
			add_prepare(el);
			return;
		}
		 if(cl.get(category)==null){
			msg=el.i18("fdc.project.category.not.found");
			el.setAttr("msg",msg);
			add_prepare(el);
			return;
	     }
	    
		
		 FDCProject project=new FDCProject();
		 project.setCategory(category);
		 project.setFace_pic_url(ReplySetting.getRelatImagePath(el,wxproject_id, file_name));
		 project.setIntroduction(introduction);
		 project.setLocation(location);
		 project.setLocation_pic(location_pic);
		 project.setLocation_url(generateLocationURL(location_pic, title, location));
		 project.setManager_on_visit_bonus(manager_on_visit_bonus);
		 project.setManager_sales_rate(manager_sales_rate);
		 project.setOld_cus_on_visit_bonus(old_cus_on_visit_bonus);
		 project.setOld_cus_sales_rate(old_cus_sales_rate);
		 project.setPos(project_dao.getMaxPos(wxproject_id,category));
		 project.setProject_detail(project_detail);
		 project.setStatus(status);
		 project.setTitle(title);
		 project.setTraffic(traffic);
		 project.setContact(contact);
		 project.setProperty_type(property_type);
		 project.setPrice(price);
		 project.setDeveloper(developer);
		 project.setProperty_company(property_company);
		 project.setFit(fit);
		 project.setYear_limit(year_limit);
		 project.setLocate1(locate1);
		 project.setLocate2(locate2);
		 project.setLocate3(locate3);
		 project.setManager_sales_return_desc(manager_sales_return_desc);
		 project.setOld_cus_sales_return_desc(old_cus_sales_return_desc);
		 project.setProperty_type_desc(property_type_desc);
		 project.setWxproject_id(wxproject_id);
		 try {
				pic.write(savedFile);
			} catch (Exception e) {
				e.printStackTrace();
				msg=el.i18("fdc.project.image.save.failed");
				el.setAttr("msg",msg);
	       	  	add_prepare(el);
				return;
		}
		 
		 try{
			 project_dao.insert(project);
		 }catch(SQLException e){
			 e.printStackTrace();
			 msg=el.i18("fdc.project.db.failure");
			 savedFile.delete();
		 }
		if(msg==null){
			msg=el.i18("fdc.project.add.success");
		}
		el.setAttr("msg",msg);
		
		index(el,wxproject_id);
	}
	
	private  String generateLocationURL(String location_pic,String title,String location){
		if(!location_pic.startsWith(Keys.getStr("fdc_map.baidu_static_map_url")))return "";
		Map<String,String> params=Http.getQueryString(location_pic);
		if(params==null)return "";
		String center=params.get("center");
		if(StringHelper.isNull(center))return "";
		String[] latn=center.split(",");
		if(latn==null||latn.length!=2)return "";
		center=latn[1]+","+latn[0];
		String url=String.format(Keys.getStr("fdc_map.baidu_dynamic_map_url"), center,title,location);
		return url;
	}
	
	
	
	private void delete(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long id=el.getLong("id",-1);
		if(id==-1l){
			index(el,wxproject_id);
			return;
		}
		
		FDCProject p=project_dao.get(id);
		if(p==null){
			el.setAttr("msg",el.i18("fdc.project.not.exists"));
			index(el,wxproject_id);
			return;
		}
		
		if(grah_dao.count(id)>0){
			el.setAttr("msg",el.i18("fdc.project.grah.is.not.empty"));
			index(el,wxproject_id);
			return;
		}
		
		
		File f=new File(el.getRealPath(p.getFace_pic_url()));
		
		String msg=null;
		try{
			project_dao.delete(id);
		}catch(Exception e){
			e.printStackTrace();
			msg=el.i18("fdc.project.db.failure");
		}
		
		if(msg==null){
			msg=el.i18("fdc.project.delete.success");
			f.delete();
		}
		el.setAttr("msg", msg);
		
		index(el,wxproject_id);
	}
	
	private void update(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
        if(!el.isMultipartContent()){
        	index(el,wxproject_id);
        	return;
        }
        String msg=null;
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        
        FilePostForm post_form=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
        if(post_form.getErrorMsg()!=null){
        	 msg=el.i18("fdc.project.update.failed")+","+post_form.getErrorMsg();
        	 el.setAttr("msg", msg);
        	 index(el,wxproject_id);
             return;
        }
        FileItem pic=post_form.getFileItem(0);
        
        
        File savedFile=new File(file_path);
        if(!savedFile.getParentFile().exists()){
          	 savedFile.getParentFile().mkdirs();
        }
       
        long id=post_form.getLong("id",-1);
        String title=post_form.getStr("title");
        String introduction=post_form.getStr("introduction");
        String traffic=post_form.getStr("traffic");
        String project_detail=post_form.getStr("project_detail");
        
        
        String location=post_form.getStr("location");
        String location_pic=post_form.getStr("location_pic");
        float manager_on_visit_bonus=post_form.getFloat("manager_on_visit_bonus",0);
        float old_cus_on_visit_bonus=post_form.getFloat("old_cus_on_visit_bonus",0);
        float manager_sales_rate=post_form.getFloat("manager_sales_rate",0);
        float old_cus_sales_rate=post_form.getFloat("old_cus_sales_rate",0);
        int category=post_form.getInt("category",0);
        int status=post_form.getInt("status",FDCProjectStatus.readytosale.getCode());
        String face_pic_url=post_form.getStr("pic_url");
        int pos=post_form.getInt("pos");
        String contact=post_form.getStr("contact");
        String price=post_form.getStr("price");
        String developer=post_form.getStr("developer");
        String property_company=post_form.getStr("property_company");
        String property_type_desc=post_form.getStr("property_type_desc");
        int fit=post_form.getInt("fit");
        int year_limit=post_form.getInt("year_limit");
        int property_type=post_form.getInt("property_type");
        int locate1=post_form.getInt("locate1");
        int locate2=post_form.getInt("locate2");
        int locate3=post_form.getInt("locate3");
		 String manager_sales_return_desc=post_form.getStr("manager_sales_return_desc");
	     String old_cus_sales_return_desc=post_form.getStr("old_cus_sales_return_desc");
	     
        if(id==-1){
			index(el,wxproject_id);
			return;
		}
        
        
        if(!project_dao.exists(id)){
        	el.setAttr("msg",el.i18("fdc.project.not.exists"));
			index(el,wxproject_id);
			return;
        }
        
        el.setAttr("id", id);
        
        if(StringHelper.isNull(title)){
			msg=el.i18("fdc.project.title.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
        
        if(StringHelper.isNull(location)){
			msg=el.i18("fdc.project.location.cannot.be.empty");
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("fdc_project_validation.title_max_length")){
			msg=String.format(el.i18("fdc.project.title.max.length.exceed"),Keys.getInt("fdc_project_validation.title_max_length"));
			el.setAttr("msg", msg);
			detail(el,wxproject_id);
			return;
		}
		
		 if(StringHelper.isNull(location)){
				msg=el.i18("fdc.project.location.cannot.be.empty");
				el.setAttr("msg",msg);
				detail(el,wxproject_id);
				return;
			}
		
		 if(cl.get(category)==null){
			 msg=el.i18("fdc.project.category.not.found");
			 el.setAttr("msg", msg);
			 detail(el,wxproject_id);
			return;
	     }
		 if(pic!=null&&pic.getName().toLowerCase().endsWith(".jpg")){
			 try {
					pic.write(savedFile);
				} catch (Exception e) {
					e.printStackTrace();
					msg=el.i18("fdc.project.image.save.failed");
					el.setAttr("msg", msg);
					detail(el,wxproject_id);
					return;
			}
			 face_pic_url=ReplySetting.getRelatImagePath(el,wxproject_id, file_name);
	     }
		 
		
		 FDCProject project=new FDCProject();
		 project.setId(id);
		 project.setCategory(category);
		 project.setFace_pic_url(face_pic_url);
		 project.setIntroduction(introduction);
		 project.setLocation(location);
		 project.setLocation_pic(location_pic);
		 project.setLocation_url(generateLocationURL(location_pic, title, location));
		 project.setManager_on_visit_bonus(manager_on_visit_bonus);
		 project.setManager_sales_rate(manager_sales_rate);
		 project.setOld_cus_on_visit_bonus(old_cus_on_visit_bonus);
		 project.setOld_cus_sales_rate(old_cus_sales_rate);
		 project.setPos(pos);
		 project.setProject_detail(project_detail);
		 project.setStatus(status);
		 project.setTitle(title);
		 project.setTraffic(traffic);
		 project.setContact(contact);
		 project.setPrice(price);
		 project.setDeveloper(developer);
		 project.setProperty_company(property_company);
		 project.setFit(fit);
		 project.setYear_limit(year_limit);
		 project.setProperty_type(property_type);
		 project.setLocate1(locate1);
		 project.setLocate2(locate2);
		 project.setLocate3(locate3);
		 project.setManager_sales_return_desc(manager_sales_return_desc);
		 project.setOld_cus_sales_return_desc(old_cus_sales_return_desc);
	     project.setProperty_type_desc(property_type_desc);
	     
		 project_dao.update(project);
		
		if(msg==null){
			msg=el.i18("fdc.project.update.success");
		}
		el.setAttr("msg", msg);
		detail(el,wxproject_id);
	}
	
	private void update_status(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		int status=el.getInt("status",-1);
		long id=el.getLong("id",-1);
		if(status==-1){
			index(el,wxproject_id);
			return;
		}
		if(id==-1){
			index(el,wxproject_id);
			return;
		}
		int category=el.getInt("category");
		
		if(!project_dao.exists(id)){
			el.setAttr("msg", el.i18("fdc.project.not.exists"));
			index(el,wxproject_id);
			return;
		}
		
		project_dao.update_status(id,status,category);
		
		el.setAttr("msg", el.i18("fdc.project.update.status.success"));
		
		index(el,wxproject_id);
		
	}
	
	public static void main(String[] args){
		System.out.println("http://api.map.baidu.com/marker?location=116.18219,39.932195&title="+Http.encode("中国铁建耀中心")+"&name="+Http.encode("中国铁建耀中心")+"&content="+Http.encode("石景山区苹果园地铁口西侧")+"&output=html");
	}
	

}
